package com.kova.api.limit;

import java.util.concurrent.ConcurrentHashMap;

public class RequestLimiter {

    private  ConcurrentHashMap<String,Long> requestMap = new ConcurrentHashMap<>();

    private static volatile RequestLimiter instance;

    private RequestLimiter() {}

    public static RequestLimiter getInstance() {
        if (instance == null) {
            synchronized (RequestLimiter.class) {
                if (instance == null) {
                    instance = new RequestLimiter();
                }
            }
        }
        return instance;
    }

    public boolean allowRequest(String userId,long timeLimit) {
        Long lastRequestTime = requestMap.get(userId);
        long currentTime = System.currentTimeMillis();
        if (lastRequestTime == null || (currentTime - lastRequestTime) > timeLimit)
        { // 允许请求并更新请求时间
             requestMap.put(userId, currentTime);
             return true;
        }
        return false; // 拒绝请求
     }
}
